import 'dart:math';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:get/get.dart';

// 可以拖动改变高度的面板
class DragPanelWidget extends StatefulWidget {
  final Widget child;

  //高度
  final double? minHeight;
  final double? maxHeight;

  //高度 屏幕比例
  final double minHeightScreenFactor;
  final double maxHeightScreenFactor;

  final double? defaultHeight;

  //宽度
  final double? minWidth;
  final double? maxWidth;

  //宽度  屏幕比例
  final double minWidthScreenFactor;
  final double maxWidthScreenFactor;

  final double? defaultWidth;

  //上下左右
  final bool isTop;
  final bool isLeft;
  final bool isBottom;
  final bool isRight;

  //对齐
  final Alignment alignment;

  const DragPanelWidget({
    super.key,
    this.minHeight,
    this.maxHeight,
    this.minHeightScreenFactor = 0.2,
    this.maxHeightScreenFactor = 0.8,
    this.defaultHeight,
    this.minWidth,
    this.maxWidth,
    this.minWidthScreenFactor = 0.2,
    this.maxWidthScreenFactor = 0.8,
    this.defaultWidth,
    this.isTop = false,
    this.isLeft = false,
    this.isBottom = false,
    this.isRight = false,
    required this.child,
    this.alignment = Alignment.bottomCenter,
  });

  @override
  State<StatefulWidget> createState() => _DragPanelWidgetState();
}

class _DragPanelWidgetState extends State<DragPanelWidget> {
  double screenWidth = 0;
  double screenHeight = 0;

  // 开始拖动后鼠标样式
  final _mouseCursor = SystemMouseCursors.basic.obs;

  // 是否正在拖动
  final _isDragging = false.obs;

  //调整大小开始的位置，上下左右
  Alignment? _resizeStartPosition = null;

  // 调整大小时鼠标移动的距离
  final double _resizeDelta = 8;
  final double _resizeDeltaStart = 20;

  // 窗口高度
  final _height = 0.0.obs;

  // 窗口宽度
  final _width = 0.0.obs;

  // 拖动开始位置
  double _dragStartX = 0;
  double _dragStartY = 0;

  // 拖动开始大小
  double _dragStartHeight = 0;
  double _dragStartWidth = 0;
  double _minHeight = 0;
  double _maxHeight = 0;
  double _minWidth = 0;
  double _maxWidth = 0;
  bool _isInit = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void didUpdateWidget(covariant DragPanelWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.minHeight != widget.minHeight ||
        widget.maxHeight != oldWidget.maxHeight ||
        widget.defaultHeight != oldWidget.defaultHeight ||
        widget.minHeightScreenFactor != oldWidget.minHeightScreenFactor ||
        widget.maxHeightScreenFactor != oldWidget.maxHeightScreenFactor) {
      if (widget.defaultHeight != oldWidget.defaultHeight) {
        _height.value = widget.defaultHeight!.clamp(_minHeight, _maxHeight);
      }
      _setMinMaxHeight();
    }
    if (oldWidget.minWidth != widget.minWidth ||
        widget.maxWidth != oldWidget.maxWidth ||
        widget.defaultWidth != oldWidget.defaultWidth ||
        widget.minWidthScreenFactor != oldWidget.minWidthScreenFactor ||
        widget.maxWidthScreenFactor != oldWidget.maxWidthScreenFactor ||
        widget.minWidthScreenFactor != oldWidget.minWidthScreenFactor ||
        widget.maxWidthScreenFactor != oldWidget.maxWidthScreenFactor) {
      if (widget.defaultWidth != oldWidget.defaultWidth) {
        _width.value = widget.defaultWidth!.clamp(_minWidth, _maxWidth);
      }
      _setMinMaxWidth();
    }
  }

  // 设置最小最大高度
  void _setMinMaxHeight() {
    if (widget.isTop || widget.isBottom) {
      _minHeight = widget.minHeight ?? screenHeight * widget.minHeightScreenFactor;
      _maxHeight = widget.maxHeight ?? screenHeight * widget.maxHeightScreenFactor;
      _height.value = _height.value.clamp(_minHeight, _maxHeight);
      print("_minHeight=$_minHeight,,, _maxHeight=$_maxHeight");
    } else {
      _height.value = widget.defaultHeight ?? double.infinity;
    }
  }

  // 设置最小最大宽度
  void _setMinMaxWidth() {
    if (widget.isLeft || widget.isRight) {
      _minWidth = widget.minWidth ?? screenWidth * widget.minWidthScreenFactor;
      _maxWidth = widget.maxWidth ?? screenWidth * widget.maxWidthScreenFactor;
      _width.value = _width.value.clamp(_minWidth, _maxWidth);
      print("_minWidth=$_minWidth,,, _maxWidth=$_maxWidth");
    } else {
      _width.value = widget.defaultWidth ?? double.infinity;
    }
  }

  SystemMouseCursor getCursorBasedOnPosition(Offset position) {
    if (position.dy < _resizeDelta) {
      //上
      if (widget.isTop) {
        return SystemMouseCursors.resizeUpDown;
      }
    } else if (position.dx < _resizeDelta) {
      //左
      if (widget.isLeft) {
        return SystemMouseCursors.resizeLeftRight;
      }
    } else if (position.dy > _height.value - _resizeDelta) {
      //下
      if (widget.isBottom) {
        return SystemMouseCursors.resizeUpDown;
      }
    } else if (position.dx > _width.value - _resizeDelta) {
      //右
      if (widget.isRight) {
        return SystemMouseCursors.resizeLeftRight;
      }
    }
    return SystemMouseCursors.basic;
  }

  void _onDragStart(DragStartDetails details) {
    _resizeStartPosition = null;
    //判断是否在顶部边缘
    if (details.localPosition.dy < _resizeDeltaStart) {
      //上
      if (widget.isTop) {
        _resizeStartPosition = Alignment.topCenter;
      }
    } else if (details.localPosition.dx < _resizeDeltaStart) {
      //左
      if (widget.isLeft) {
        _resizeStartPosition = Alignment.centerLeft;
      }
    } else if (details.localPosition.dy > _height.value - _resizeDeltaStart) {
      //下
      if (widget.isBottom) {
        _resizeStartPosition = Alignment.bottomCenter;
      }
    } else if (details.localPosition.dx > _width.value - _resizeDeltaStart) {
      //右
      if (widget.isRight) {
        _resizeStartPosition = Alignment.centerRight;
      }
    }
    print("_onDragStart:$details，，，，${details.localPosition.dy},_resizeStartPosition = $_resizeStartPosition");

    if (_resizeStartPosition != null) {
      _isDragging.value = true;
      _dragStartX = details.globalPosition.dx;
      _dragStartY = details.globalPosition.dy;
      _dragStartHeight = _height.value;
      _dragStartWidth = _width.value;
    }
  }

  void _onDragUpdate(DragUpdateDetails details) {
    if (!_isDragging.value) return;
    final double deltaY = details.globalPosition.dy - _dragStartY;
    final double deltaX = details.globalPosition.dx - _dragStartX;
    switch (_resizeStartPosition) {
      case Alignment.topCenter:
        //上
        final double newHeight = _dragStartHeight - deltaY;
        _height.value = newHeight.clamp(_minHeight, _maxHeight);
        break;
      case Alignment.bottomCenter:
        //下
        final double newHeight = _dragStartHeight + deltaY;
        _height.value = newHeight.clamp(_minHeight, _maxHeight);
        break;
      case Alignment.centerLeft:
        //左
        final double newWidth = _dragStartWidth - deltaX;
        _width.value = newWidth.clamp(_minWidth, _maxWidth);
        break;
      case Alignment.centerRight:
        //右
        final double newWidth = _dragStartWidth + deltaX;
        _width.value = newWidth.clamp(_minWidth, _maxWidth);
        break;
    }
  }

  void _onDragEnd(DragEndDetails details) {
    _isDragging.value = false;
  }

  @override
  Widget build(BuildContext context) {
    //每次都刷新屏幕大小
    final newScreenWidth = MediaQuery.of(context).size.width;
    final newScreenHeight = MediaQuery.of(context).size.height;
    // 位置改变，吸附的地方也得改变
    bool sizeIsChanged = screenWidth != newScreenWidth || screenHeight != newScreenHeight;
    screenWidth = newScreenWidth;
    screenHeight = newScreenHeight;
    if (sizeIsChanged) {
      _setMinMaxHeight();
      _setMinMaxWidth();
    }
    //初始化位置
    if (!_isInit) {
      _isInit = true;
      _height.value = widget.defaultHeight ?? _minHeight;
      _width.value = widget.defaultWidth ?? _minWidth;
      if (_height.value <= 0) {
        _height.value = max(screenHeight * 0.2, 160);
      }
      if (_width.value <= 0) {
        _width.value = max(screenWidth * 0.2, 60);
      }
    }
    print("height = $_height,,width = $_width,,_minHeight=$_minHeight");
    return Align(
      alignment: widget.alignment,
      // 调整窗口大小 手势
      child: GestureDetector(
        onVerticalDragStart: _onDragStart,
        onVerticalDragUpdate: _onDragUpdate,
        onVerticalDragEnd: _onDragEnd,
        behavior: HitTestBehavior.translucent,
        // 设置鼠标指针
        child: Obx(
          () => MouseRegion(
            cursor: _mouseCursor.value,
            //鼠标移动事件，设置鼠标样式，并设置调整方向
            onHover: (PointerHoverEvent event) {
              // LogUtils.i("onHover:$event");
              if (!_isDragging.value) {
                _mouseCursor.value = getCursorBasedOnPosition(event.localPosition);
                // print("getCursorBasedOnPosition:${event.localPosition},_mouseCursor.value=${_mouseCursor.value}");
              }
            },
            child: Obx(
              () => Container(
                width: _width.value,
                height: _height.value,
                decoration: BoxDecoration(
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(color: Theme.of(context).shadowColor, blurRadius: 10),
                  ],
                  borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
                ),
                child: widget.child,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
